class Texture extends Asset {
  html.WebGLTexture _handle;
  int _width;
  int _height;

  html.WebGLTexture get handle() => _handle;
  int get width() => _width;
  int get height() => _height;
  
  static Graphics _graphics;
  static Map<String, Texture> _cache;
  factory Texture(String uri) {
    uri = uri.toLowerCase();
    
    if (_cache == null)
      _cache = {};
    
    Texture result = _cache[uri];
    if (result != null)
      return result;
    
    result = new Texture._internal(uri);
    _cache[uri] = result;
    return result;
  }
  
  Texture._internal(String uri) {
    _width = 0;
    _height = 0;
    
    Texture me = this;
    
    html.ImageElement img = new html.Element.tag('img');
    img.on.load.add((e) {
      final gl = _graphics.gl;
      final texture = gl.createTexture();
      gl.bindTexture(html.WebGLRenderingContext.TEXTURE_2D, texture);
      gl.pixelStorei(html.WebGLRenderingContext.UNPACK_FLIP_Y_WEBGL, 1);
      gl.texImage2D(html.WebGLRenderingContext.TEXTURE_2D, 0,
        html.WebGLRenderingContext.RGBA,
        html.WebGLRenderingContext.RGBA,
        html.WebGLRenderingContext.UNSIGNED_BYTE,
        img);
      gl.texParameteri(html.WebGLRenderingContext.TEXTURE_2D,
        html.WebGLRenderingContext.TEXTURE_MAG_FILTER,
        html.WebGLRenderingContext.LINEAR);
      gl.texParameteri(html.WebGLRenderingContext.TEXTURE_2D,
        html.WebGLRenderingContext.TEXTURE_MIN_FILTER,
        html.WebGLRenderingContext.LINEAR);
      //gl.bindTexture(WebGLRenderingContext.TEXTURE_2D, null);
      me._width = 32;//img.width;
      me._height = 64;//img.height;
      me._handle = texture;
      me.status = Asset.LOADED;
    }, false);
    img.on.error.add((e) {
      me.status = Asset.NOT_FOUND;
    }, false);
    img.src = uri;
  }
}